<template>
  <div class="app-container">
    <loading v-show="loading"></loading>
    <el-card class="box-card searchFormStyle" style="margin-bottom:1%;">
      <div slot="header" class="clearfix">
        <span>试卷操作</span>
      </div>
      <div class="text item">
        <el-form ref="searchData" :model="searchData" label-width="130px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="试卷标题">
                <el-input v-model="searchData.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="试卷类型">
                <el-select v-model="searchData.status" placeholder="请选择试卷类型" class="tree-select">
                  <el-option
                    v-for="item in Status"
                    :key="item.paramValue"
                    :label="item.paramName"
                    :value="item.paramValue">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item>
                <el-button type="primary" 
                icon="el-icon-plus" 
                v-if="permissionHandle('examPaper:openDialog')"
                @click="openDialog">新 增</el-button>
                <el-button type="primary" 
                icon="el-icon-search" 
                v-if="permissionHandle('examPaper:getList')"
                @click="getList">查 询</el-button>
                <el-button type="primary" 
                icon="el-icon-refresh" 
                v-if="permissionHandle('examPaper:getList')"
                @click="resetSearch">重 置</el-button>
                <el-button type="info" 
                icon="el-icon-delete" 
                v-if="permissionHandle('examPaper:handleDelete')"
                @click="deletePaper">删 除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-bottom:1%;">
        <div slot="header" class="clearfix">
          <span>试卷列表</span>
          <div class="btn-box">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-download"
              style="margin-right:20px"><a :href="fileUrl">试卷模板下载</a></el-button>
          </div>
        </div>
        <el-table
          :data="tableData"
          border
          ref="tableData"
          style="width: 100%;margin-bottom:1%;"
          @selection-change="handleSelectionChange"
          >
          <el-table-column
            type="selection"
            width="40">
          </el-table-column>
          <el-table-column
            label="试卷标题"
            width="180">
            <template slot-scope="scope">
                {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column
            label="卷面总分值"
            width="100"
          >
            <template slot-scope="scope">
                {{ scope.row.totalScore }}
            </template>
          </el-table-column>
          <el-table-column
            label="及格百分比"
            width="100">
            <template slot-scope="scope">
                {{ scope.row.passPercentage }}
            </template>
          </el-table-column>
          <el-table-column
            label="考试开始时间"
          >
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.startTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="考试结束时间"
          >
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            label="考试状态"
          >
            <template slot-scope="scope">
                {{ scope.row.status }}
            </template>
          </el-table-column>
          <el-table-column
            label="试题顺序"
            width="100">
            <template slot-scope="scope">
                {{ scope.row.questionOrder }}
            </template>
          </el-table-column>
          <el-table-column
            label="试卷描述"
            width="180">
            <template slot-scope="scope">
                {{ scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="300px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                v-if="scope.row.status !== '已开考' && scope.row.status !== '已结束' && permissionHandle('examPaper:handleEdit')"
                icon="el-icon-edit-outline"
                @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :show-file-list="false"
                  :action="importFileUrl"
                  :data="importData"
                  :headers="myHeaders"
                  :beforeUpload="beforeAvatarUpload"
                  :onError="uploadError"
                  :onSuccess="uploadSuccess"
                  accept="excel"
                  >
                  <el-button style="margin-left: 10px;" size="small" v-if="scope.row.status !== '已开考' && scope.row.status !== '已结束'"  @click="getId(scope.$index, scope.row)" icon="el-icon-edit-outline">上传试题</el-button>
                </el-upload>
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="danger"
                v-if="permissionHandle('examPaper:handleDelete')"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <pagination @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange" :paginations="paginations"></pagination>
    </el-card>
    <el-dialog  fullscreen :title="dialogTitle" :visible.sync="dialogVisible" width="90%">
      <add-panel @savaSuccess="savaSuccess" @loadingShow="loadingShow" @loadingHide="loadingHide" :testTypeList="testTypeLists" :detailData="detailData"></add-panel>
    </el-dialog>
  </div>
</template>
<script>
import Loading from '@/components/loading/loading'
import pagination from '@/components/pagination/index'
import addPanel from './addTest'
import { getStatus, getPaperList, deletePaper, resDetail } from '@/api/examManagement/examPaper'
import { MessageBox } from 'element-ui'
import store from '@/store'
export default {
  components: {
    Loading,
    pagination,
    addPanel
  },
  data() {
    this.permissionHandle = this.$permissionHandle
    return {
      fileUrl: 'static/files/template.xlsx',
      myHeaders: { userToken: store.getters.token },
      importFileUrl: process.env.BASE_API + '/test/excel',
      importData: {
        infoId: ''
      },
      paginations: {
        totalNum: 0,
        currentPage: 1,
        pageSize: 10
      },
      searchData: {
        name: '',
        status: '',
        pageSize: '10',
        pageNum: '1'
      },
      dialogVisible: false,
      dialogTitle: '新增试卷',
      loading: false,
      Status: [],
      tableData: [],
      multipleSelection: [],
      deleteDepArry: [],
      testTypeLists: [],
      searchDetail: {
        key: ''
      },
      detailData: {},
      params: {}
    }
  },
  created() {
    this.getStatu()
    this.getList()
  },
  methods: {
    resetSearch() {
      this.searchData.name = ''
      this.searchData.status = ''
      this.getList()
    },
    // 上传成功后的回调
    uploadSuccess(response, file, fileList) {
      if (response.code !== 200) {
        this.$message({
          message: response.msg,
          type: 'warning',
          duration: 3000
        })
        if (response.code === 401) {
          MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
        }
      }
      if (response.code === 200) {
        this.$message({
          message: response.msg,
          type: 'success'
        })
      }
    },
    getId(index, row) {
      this.importData.infoId = row.id
    },
    // 上传错误
    uploadError(response, file, fileList) {
      this.$message({
        message: response.msg,
        type: 'warning',
        duration: 0,
        showClose: true
      })
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file, index, row) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      if (!extension && !extension2) {
        this.$message({
          message: '上传的试卷模板只能是 xls、xlsx格式!',
          type: 'warning'
        })
      }
      return extension || extension2
    },
    blurSearch() {
      this.searchData.pageNum = 1
      this.getList()
      this.paginations.currentPage = 1
    },
    // 打开新增弹出框
    openDialog() {
      this.dialogVisible = true
      this.dialogTitle = '新增试卷'
      this.getDetail('add')
    },
    getDetail(paramter) {
      this.loading = true
      resDetail(this.searchDetail).then(response => {
        this.testTypeLists = response.data.questionsType
        if (paramter === 'edit') {
          this.detailData = response.data
        } else {
          this.detailData = {}
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    // 获取列表
    getList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getPaperList(this.searchData).then(response => {
          this.tableData = response.data.items
          this.paginations.totalNum = parseInt(response.data.itemsTotalCount)
          resolve()
          this.loading = false
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },
    // 删除
    deletePaper() {
      if (this.deleteDepArry.length) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return new Promise((resolve, reject) => {
            deletePaper({ 'keys': JSON.stringify(this.deleteDepArry) }).then(response => {
              resolve()
              this.loading = false
              this.getList()
              this.deleteDepArry = []
            }).catch(error => {
              this.loading = false
              this.deleteDepArry = []
              reject(error)
            })
          })
        }).catch(() => {
          this.deleteDepArry = []
          this.$refs.tableData.clearSelection()
          return
        })
      } else {
        this.$message({
          showClose: true,
          message: '请至少选择一条要删除的数据',
          type: 'warning'
        })
      }
    },
    getStatu() {
      getStatus('').then(response => {
        this.Status = response.data
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    handleSelectionChange(val) {
      this.deleteDepArry = []
      this.multipleSelection = val
      this.multipleSelection.forEach(element => {
        this.deleteDepArry.push(element.id)
      })
    },
    // 改变分页的时候查询数据
    handleSizeChange(val) {
      this.SearchDep.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.SearchDep.pageNum = val
      this.getList()
    },
    handleDelete(index, row) {
      this.deleteDepArry = []
      this.deleteDepArry.push(row.id)
      this.deletePaper()
    },
    handleEdit(index, row) {
      this.dialogVisible = true
      this.dialogTitle = '修改试卷'
      this.searchDetail.key = row.id
      this.getDetail('edit')
    },
    savaSuccess() {
      this.loading = false
      this.dialogVisible = false
      this.getList()
    },
    loadingShow() {
      this.loading = true
    },
    loadingHide() {
      this.loading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-demo{display: inline-block;}
</style>
